package console4.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.concurrent.Semaphore;

import console4.widgets.ConsoleTextPane;


public class InputStreamGobbler extends Thread {
	
	private ConsoleTextPane consoleTextPane;
	private Semaphore printSemaphore;
	private InputStream inputStream;
	private boolean errorStream;
	
	public InputStreamGobbler(ConsoleTextPane consoleTextPane, Semaphore printSemaphore, InputStream inputStream, boolean errorStream) {
		this.consoleTextPane=consoleTextPane;
		this.printSemaphore=printSemaphore;
		this.inputStream=inputStream;
		this.errorStream=errorStream;
	}

	@Override
	public void run() {
		
		try {
			final BufferedReader r = new BufferedReader(new InputStreamReader(inputStream,"IBM00858"));
			char c = Character.MAX_VALUE;
			boolean hasSemaphore=false;
			StringBuilder sb=new StringBuilder();
			while ((c = (char) r.read()) != Character.MAX_VALUE) {
				if(!hasSemaphore) {
					printSemaphore.acquire();
					sb=new StringBuilder();
					hasSemaphore=true;
				}
				sb.append(c);
				if(!r.ready()) {
					consoleTextPane.addTextToPane(sb.toString(),errorStream);
					printSemaphore.release();
					hasSemaphore=false;
				}
			}
		} catch (IOException | InterruptedException e) {
			e.printStackTrace();
		}
	}
}
